package cmd

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"webmsg/config"
)

var (
	cfgFile string
	rootCmd = &cobra.Command{
		Use:   "webmsg run [flags] [value]",
		Short: "webmsg run",
		Long:  "                __                        \n _      _____  / /_  ____ ___  _________ _\n| | /| / / _ \\/ __ \\/ __ `__ \\/ ___/ __ `/\n| |/ |/ /  __/ /_/ / / / / / (__  ) /_/ / \n|__/|__/\\___/_.___/_/ /_/ /_/____/\\__, /  \n                                 /____/   \n",
	}
	cfg            *config.Config
	logrusLevelMap = map[string]logrus.Level{
		"panic": logrus.PanicLevel,
		"fatal": logrus.FatalLevel,
		"error": logrus.ErrorLevel,
		"warn":  logrus.WarnLevel,
		"info":  logrus.InfoLevel,
		"debug": logrus.DebugLevel,
		"trace": logrus.TraceLevel,
	}
)

func init() {
	cobra.OnInitialize(initialize)
	// 全局flags
	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file, default is $HOME/.webmsg/webmsg.yml.")
}

func initialize() {
	var (
		lv logrus.Level
		ok bool
		err error
	)
	fmt.Println(rootCmd.Long)
	logrus.SetFormatter(&logrus.TextFormatter{FullTimestamp: true})

	config.Initialize(cfgFile)
	logrus.WithFields(logrus.Fields{"method": "Initialize"}).Info("Custom configuration file: ", cfgFile)

	cfg, err = config.GetConfig()
	if err != nil {
		logrus.Fatal(err)
	}
	logrus.WithFields(logrus.Fields{"method": "Initialize"}).Info("Configuration file currently in use: ", viper.ConfigFileUsed())

	// 设置日志工具
	lv, ok = logrusLevelMap[cfg.LogLevel]
	if !ok {
		logrus.Fatal("Log level can only be one of trace, debug, info, warn, error, fatal, panic")
	}
	logrus.SetLevel(lv)

	// 设置gin
	if lv >= logrus.DebugLevel {
		gin.SetMode(gin.DebugMode)
	} else {
		gin.SetMode(gin.ReleaseMode)
	}
}

// Execute 执行命令，随着命令树执行
func Execute() error {
	return rootCmd.Execute()
}
